<template>
  <div class="search-select-container" ref="containerRef">
    <!-- 搜索输入框 -->
    <el-input
      v-model="searchQuery"
      :placeholder="placeholder || '请输入关键词搜索...'"
      @focus="handleFocus"
      @input="handleInput"
      @blur="handleBlur"
      clearable
      :class="{ 'active': isShowDropdown }"
    />

    <!-- 悬浮表格下拉框 -->
    <el-popover
      v-model:visible="isShowDropdown"
      :virtual-triggering="true"
      :virtual-ref="containerRef"
      placement="bottom-start"
      :width="dropdownWidth"
      trigger="manual"
      @hide="handleDropdownHide"
    >
      <template #default>
        <div class="dropdown-content">
          <!-- 表格展示数据 -->
          <el-table
            :data="filteredData"
            border
            highlight-current-row
            @row-click="handleRowClick"
            :max-height="maxHeight"
          >
            <!-- 动态渲染表格列 -->
            <el-table-column
              v-for="column in columns"
              :key="column.prop"
              :prop="column.prop"
              :label="column.label"
              :width="column.width"
              :align="column.align || 'left'"
            />
          </el-table>

          <!-- 无数据提示 -->
          <div v-if="filteredData.length === 0" class="no-data">
            没有找到匹配的数据
          </div>
        </div>
      </template>
    </el-popover>
  </div>
</template>

<script setup>
import { ref, watch, nextTick, computed } from 'vue';

// 组件属性
const props = defineProps({
  // 数据源
  data: {
    type: Array,
    default: () => [],
    required: true
  },
  // 表格列配置
  columns: {
    type: Array,
    default: () => [],
    required: true
  },
  // 搜索框占位符
  placeholder: {
    type: String,
    default: '请输入关键词搜索...'
  },
  // 下拉框最大高度
  maxHeight: {
    type: Number,
    default: 300
  },
  // 搜索匹配的字段，默认匹配所有字段
  searchFields: {
    type: Array,
    default: null
  }
});

// 组件事件
const emit = defineEmits(['select', 'update:modelValue']);

// 响应式变量
const searchQuery = ref('');
const isShowDropdown = ref(false);
const containerRef = ref(null);
const dropdownWidth = ref('auto');
const rawData = ref([...props.data]);

// 监听数据源变化
watch(
  () => props.data,
  (newVal) => {
    rawData.value = [...newVal];
  },
  { deep: true }
);

// 过滤后的数据
const filteredData = computed(() => {
  if (!searchQuery.value.trim()) {
    return rawData.value;
  }
  
  const query = searchQuery.value.toLowerCase().trim();
  
  return rawData.value.filter(item => {
    // 如果指定了搜索字段，则只在指定字段中搜索
    if (props.searchFields && props.searchFields.length) {
      return props.searchFields.some(field => {
        const value = item[field];
        return value !== null && value !== undefined && 
               String(value).toLowerCase().includes(query);
      });
    }
    
    // 否则在所有字段中搜索
    return Object.values(item).some(value => {
      return value !== null && value !== undefined && 
             String(value).toLowerCase().includes(query);
    });
  });
});

// 处理输入框获得焦点
const handleFocus = () => {
  nextTick(() => {
    isShowDropdown.value = true;
    // 设置下拉框宽度与输入框一致
    if (containerRef.value) {
      dropdownWidth.value = `${containerRef.value.offsetWidth}px`;
    }
  });
};

// 处理输入事件
const handleInput = () => {
  if (!isShowDropdown.value) {
    isShowDropdown.value = true;
  }
};

// 处理输入框失去焦点
const handleBlur = () => {
  // 延迟关闭，以便处理点击事件
  setTimeout(() => {
    isShowDropdown.value = false;
  }, 200);
};

// 处理下拉框隐藏
const handleDropdownHide = () => {
  // 可以在这里添加隐藏时的逻辑
};

// 处理表格行点击
const handleRowClick = (row) => {
  // 选中数据后关闭下拉框
  isShowDropdown.value = false;
  // 清空搜索框
  searchQuery.value = '';
  // 抛出选中的数据
  emit('select', row);
};
</script>

<style scoped>
.search-select-container {
  position: relative;
  width: 100%;
}

.el-input.active .el-input__wrapper {
  border-color: var(--el-color-primary);
  box-shadow: 0 0 0 2px rgba(var(--el-color-primary-rgb), 0.2);
}

.dropdown-content {
  width: 100%;
}

.no-data {
  text-align: center;
  padding: 16px;
  color: var(--el-text-color-secondary);
}

.el-table {
  width: 100%;
  border-radius: 4px;
}

.el-table__row {
  cursor: pointer;
}
</style>
